<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\PayConfig;
use app\admin\model\ProductMessage;
use app\admin\model\Configuration;
use app\admin\model\Payment;
use app\admin\model\Shop;
use app\admin\model\ShopOrder;
use app\admin\model\ShopPriceLog;
use app\admin\model\Product;
use app\admin\model\UserOrder;
use getui\GeTui;
use addons\shopro\library\AdapayService;
use think\Db;
use think\Log;
use think\Exception;
use think\Session;

class Pay extends Api
{
	protected $noNeedLogin = ['notifyx'];
	protected $appid;
	protected $secret;

	public function _initialize(){
		$action = request()->action();
		$ignore = array('host','accept','content-length','content-type');
		$headers = array();
		if($this->request->request('token')){
			$headers['token'] = $this->request->request('token');
		}else{
			foreach($_SERVER as $key=>$value){
				if(substr($key, 0, 5)==='HTTP_'){
					$key = substr($key, 5);
					$key = str_replace('_', ' ', $key);
					$key = str_replace(' ', '-', $key);
					$key = strtolower($key);
					if(!in_array($key, $ignore)){
						$headers[$key] = $value;
					}
				}
			}
		}
		if(empty($headers['token']) && in_array($action,$this->noNeedLogin)){
			//当未传token并且控制器可不不传token情况下不需要验证登录
		}else{
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
		
        $this->appid = 'wx7e02d2ebf871c207';
        $this->secret = '1048ec4292504f8f4b1423b205ddb9b8';

	}
    //创建预支付订单
    public function create_order(){
        $product_id = $this->request->post('product_id','');
        $price = $this->request->post('price','');
        $address_username = $this->request->post('address_username','');
        $address_tel = $this->request->post('address_tel','');
        $address_province = $this->request->post('address_province','');
        $address_city = $this->request->post('address_city','');
        $address_district = $this->request->post('address_district','');
        $address_detail = $this->request->post('address_detail','');
        $product = Product::where(['id'=>$product_id,'is_sale'=>0,'is_del'=>0,'status'=>1])->find();
        if(!$product){
            $this->error('未查询到商品或已售出!');
        }
        if($product['user_id'] == $this->user['id']){
            $this->error('无法兑换自己的物品!');
        }
        if($product['price']>$this->user['rose_money']){
            $this->error('余额不足，兑换失败!');
        }
        $data = [
            'user_id'=>$this->user['id'],
            'order_id'=>date("YmdHis").rand(1000,9999),
            'product_id'=>$product_id,
            'price'=>$product['price'],
            'money'=>$price,
            'ship_type'=>1,
            'shop_id'=>$product['user_id'],
            'add_time'=>time(),
            'total_money'=>$product['price'],
            'address_username'=>$address_username == 'undefined' ? '' : $address_username,
            'address_tel'=>$address_tel == 'undefined' ? '' : $address_tel,
            'address_province'=>$address_province == 'undefined' ? '' : $address_province,
            'address_city'=>$address_city == 'undefined' ? '' : $address_city,
            'address_district'=>$address_district == 'undefined' ? '' : $address_district,
            'address_detail'=>$address_detail == 'undefined' ? '' : $address_detail,
        ];
        $id = UserOrder::insertGetId($data);
        $this->success('操作成功',['id'=>$id,'order_id'=>$data['order_id']]);

    }
    //创建预支付充值订单
    public function create_shop_order(){
        $shop_id = $this->request->post('shop_id','');
        $is_ai = $this->request->post('is_ai',0);
        $num = $this->request->post('num',0);
        $activeI = $this->request->post('activeI',3);
        $price = $this->request->post('price','');
        $shop = Shop::where(['id'=>$shop_id,'status'=>1])->find();
        if(!$shop){
            $this->error('未查询到该商户信息!');
        }
        $data = [
            'user_id'=>$this->user['id'],
            'order_sn'=>date("YmdHis").rand(1000,9999),
            'shop_id'=>$shop_id,
            'price'=>$price,
            'num'=>$num,
            'is_ai'=>$is_ai,
            'add_time'=>time(),
        ];
        if($activeI == 0){
            $data['type'] = 3;
        }elseif($activeI == 1){
            $data['type'] = 2;
        }elseif($activeI == 2){
            $data['type'] = 4;
        }else{
            $data['type'] = 1;
        }
        $id = ShopOrder::insertGetId($data);
        $this->success('操作成功',['id'=>$id,'order_id'=>$data['order_sn']]);
    }
     /**
     * 商家充值拉起支付
     */
    public function shop_prepay(){
        $order_id = $this->request->post('order_id');
        $shop_id = $this->request->post('shop_id');
        $payment = $this->request->post('payment');
        $openid = $this->request->post('openid', '');
        $price = $this->request->post('price', '');
        $code = $this->request->post('code', '');
        $platform = $this->request->post('platform', 'wxMiniProgram');
        if ($platform == 'wxMiniProgram' && !$openid && $code) $openid = $this->LightOpenID($code);
        $order = ShopOrder::where('id', $order_id)->find();
        if (!$order)  {
            $this->error("订单不存在");
        }
        if($order['price'] != $price){
            $this->error("订单支付金额错误");
        }

        $order_data = [
            'out_trade_no' => $order['order_sn'],
            'total_fee' => $price,
        ];
        if($payment == 'wechat') {// 微信公众号，小程序支付，必须有 openid
            if (in_array($platform, ['wxOfficialAccount', 'wxMiniProgram'])) {
                $order_data['openid'] = $openid;
                if (empty($order_data['openid'])) {
                    return $this->success('缺少 openid', 'no_openid');
                }
            }
            $order_data['body'] = '商家充值';
        }
        $notify_url = $this->request->root(true) . '/api/pay/notifyx/payment/' . $payment . '/platform/shop';
        $pay = new PayService($payment,$platform, $notify_url);
        try {
            $result = $pay->create($order_data);
        } catch (\Yansongda\Pay\Exceptions\Exception $e) {
            $this->error("支付配置错误：" . $e->getMessage());
        }
        if ($platform == 'App') {
            $result = $result->getContent();
        }
        $row = [
            'type'=>'pay',
            'pay_type'=>$payment,
            'order_id'=>$order['id'],
            'out_trade_no'=>$order['order_sn'],
            'createtime'=>time(),
            'amount'=>$price,
            'pay_amount'=>0,
            'status'=>'loading',
            'pay_json'=>'',
            'payment_id'=>'',
            'transaction_id'=>'',
            'pay_time'=>0,
            'user_id'=>$order['user_id'],
            'platform'=>$platform,
            'use_type'=>'order',
            'shop_id'=>$shop_id
        ];
        Payment::create($row);
        $pay_method = [
            'wechat'=>'wechat',
            'alipay'=>'alipay',
            'adapay_wechat'=>'wechat',
            'adapay_alipay'=>'alipay',
            'wallet'=>'wallet',
        ];
        $this->success('获取预付款成功', [
            'pay_data' => $result,
            'pay_action' => $pay_method[$payment],
        ]);
    }
     /**
     * 拉起支付
     */
    public function prepay(){
        $order_id = $this->request->post('order_id');
        $payment = $this->request->post('payment');
        $openid = $this->request->post('openid', '');
        $price = $this->request->post('price', '');
        $code = $this->request->post('code', '');
        $platform = $this->request->post('platform', 'wxMiniProgram');
        //$platform = 'wxMiniProgram';//request()->header('platform');
        if ($platform == 'wxMiniProgram' && !$openid && $code) $openid = $this->LightOpenID($code);
        $order = UserOrder::where('id', $order_id)->find();
        if (!$order)  {$this->error("订单不存在");}
        $product = Product::where(['id'=>$order['product_id']])->find();
        $order_data = [
            'out_trade_no' => $order['order_id'],
            'total_fee' => $price,
        ];
        if($payment == 'wechat') {// 微信公众号，小程序支付，必须有 openid
            if (in_array($platform, ['wxOfficialAccount', 'wxMiniProgram'])) {
                $order_data['openid'] = $openid;
                if (empty($order_data['openid'])) {
                    return $this->success('缺少 openid', 'no_openid');
                }
            }
            $order_data['body'] = mb_substr($product['title'], 0, 30);
        }
        $notify_url = $this->request->root(true) . '/api/pay/notifyx/payment/' . $payment . '/platform/product';
        $pay = new PayService($payment,$platform, $notify_url);
        try {
            $result = $pay->create($order_data);
        } catch (\Yansongda\Pay\Exceptions\Exception $e) {
            $this->error("支付配置错误：" . $e->getMessage());
        }
        if ($platform == 'App') {
            $result = $result->getContent();
        }
        $row = [
            'type'=>'pay',
            'pay_type'=>$payment,
            'order_id'=>$order['id'],
            'out_trade_no'=>$order['order_id'],
            'createtime'=>time(),
            'amount'=>$price,
            'pay_amount'=>0,
            'status'=>'loading',
            'pay_json'=>'',
            'payment_id'=>'',
            'transaction_id'=>'',
            'pay_time'=>0,
            'user_id'=>$order['user_id'],
            'platform'=>$platform,
            'use_type'=>'order',
        ];
        Payment::create($row);
        $pay_method = [
            'wechat'=>'wechat',
            'alipay'=>'alipay',
            'adapay_wechat'=>'wechat',
            'adapay_alipay'=>'alipay',
            'wallet'=>'wallet',
        ];
        $this->success('获取预付款成功', [
            'pay_data' => $result,
            'pay_action' => $pay_method[$payment],
        ]);
    }
    /**
     * 支付成功回调
     * @return mixed
     */
    public function notifyx()
    {
        $payment = $this->request->param('payment');
        $platform = $this->request->param('platform');
        $pay = new PayService($payment, $platform);
        $result = $pay->notify(function ($data, $pay) use ($payment, $platform) {
            /* {    // 微信回调参数
                "appid":"wx39cd0799d4567dd0",
                "bank_type":"OTHERS",
                "cash_fee":"1",
                "fee_type":"CNY",
                "is_subscribe":"N",
                "mch_id":"1481069012",
                "nonce_str":"dPpcZ6AzCDU8daNC",
                "openid":"oD9ko4x7QMDQPZEuN8V5jtZjie3g",
                "out_trade_no":"202010240834057843002700",
                "result_code":"SUCCESS",
                "return_code":"SUCCESS",
                "sign":"3103B6D06F13D2B3959C5B3F7F1FD61C",
                "time_end":"20200407102424",
                "total_fee":"1",
                "trade_type":"JSAPI",
                "transaction_id":"4200000479202004070804485027"
            } */
            /*  {    // 支付宝支付成功回调参数
                "gmt_create":"2020-04-10 19:15:00",
                "charset":"utf-8",
                "seller_email":"xptech@qq.com",
                "subject":"\u5546\u57ce\u8ba2\u5355\u652f\u4ed8",
                "sign":"AOiYZ1a2mEMOuIbHFCi6V6A0LJ97UMiHsCWgNdSU9dlzKFl15Ts8b0mL\/tN+Hhskl+94S3OUiNTBD3dD0Kv923SqaTWxNdj533PCdo2GDKsZIZgKbavnOvaccSKUdmQRE9KtmePPq9V9lFzEQvdUkKq1M8KAWO5K9LTy2iT2y5CUynpiu\/04GVzsTL9PqY+LDwqj6K+w7MgceWm1BWaFWg27AXIRw7wvsFckr3k9GGajgE2fufhoCYGYtGFbhGOp6ExtqS5RXBuPODOyRhBLpD8mwpOX38Oy0X+R4YQIrOi02dhqwPpvw79YjnvgXY3qZEQ66EdUsrT7EBdcPHK0Gw==",
                "buyer_id":"2088902485164146",
                "invoice_amount":"0.01",
                "notify_id":"2020041000222191501064141414240102",
                "fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]",
                "notify_type":"trade_status_sync",
                "trade_status":"TRADE_SUCCESS",
                "receipt_amount":"0.01",
                "buyer_pay_amount":"0.01",
                "app_id":"2021001114666742",
                "sign_type":"RSA2",
                "seller_id":"2088721922277739",
                "gmt_payment":"2020-04-10 19:15:00",
                "notify_time":"2020-04-10 19:15:01",
                "version":"1.0",
                "out_trade_no":"202007144778322770017000",
                "total_amount":"0.01",
                "trade_no":"2020041022001464141443020240",
                "auth_app_id":"2021001114666742",
                "buyer_logon_id":"157***@163.com",
                "point_amount":"0.00"
            } */
            /* {   // 支付宝退款成功（交易关闭）回调参数
                "gmt_create": "2020-08-15 14:48:32",
                "charset": "utf-8",
                "seller_email": "xptech@qq.com",
                "gmt_payment": "2020-08-15 14:48:32",
                "notify_time": "2020-08-15 16:11:45",
                "subject": "商城订单支付",
                "gmt_refund": "2020-08-15 16:11:45.140",
                "sign": "b6ArkgzLIRteRL9FMGC6i\/jf6VwFYQbaGDGRx002W+pdmN5q9+O4edZ3ALF74fYaijSl9ksNr0dKdvanu3uYxBTcd\/GIS4N1CWzmCOv6pzgx5rO\/YvGoHLM3Yop0GKKuMxmnNsZ6jhYKEY7SYD3Y0L6PU9ZMdHV7yIiVj+zZmbKzUgK9MPDCEXs+nzpNAiSM8GTqYRSUvKobAK68hswG2k1QIcqr5z+ZmVYa\/nHHkoC9qXt5zwyGi4P+2eOsr6V2PjA3x8qqe7TN5aI1DeoZD5KqHPYYaYF17J2q6YPlgl3WUl1RhE7H86bivB1fIuYEv\/3+JR74WN\/o7krGw1RPHg==",
                "out_biz_no": "R202004114414846255015300",
                "buyer_id": "2088902485164146",
                "version": "1.0",
                "notify_id": "2020081500222161145064141453349793",
                "notify_type": "trade_status_sync",
                "out_trade_no": "202002460317545607015300",
                "total_amount": "0.01",
                "trade_status": "TRADE_CLOSED",
                "refund_fee": "0.01",
                "trade_no": "2020081522001464141438570535",
                "auth_app_id": "2021001114666742",
                "buyer_logon_id": "157***@163.com",
                "gmt_close": "2020-08-15 16:11:45",
                "app_id": "2021001114666742",
                "sign_type": "RSA2",
                "seller_id": "2088721922277739"
            } */
            db('log')->insert(['text'=>json_encode($data)]);
            //$data = json_decode('{"appid":"wx7e02d2ebf871c207","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1650562174","nonce_str":"ZhHilq8KWIjf1EBv","openid":"o_sKy5N0XBUBqa5hrSHRxqfIq5J4","out_trade_no":"202309071029199121","result_code":"SUCCESS","return_code":"SUCCESS","sign":"492D1BBAA4B9263D080C9D40254CE8FA","time_end":"20230907102930","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001944202309072304948815"}',true);
            try {
                $out_trade_no = $data['out_trade_no'];
                $out_refund_no = $data['out_biz_no'] ?? '';
                // 判断支付宝微信是否是支付成功状态，如果不是，直接返回响应
                if ($payment == 'alipay' && $data['trade_status'] != 'TRADE_SUCCESS') {
                    // 不是交易成功的通知，直接返回成功
                    return $pay->success()->send();
                }
                if ($payment == 'wechat' && ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS')) {
                    // 微信交易未成功，返回 false，让微信再次通知
                    return false;
                }
                // 支付成功流程
                $pay_fee = $payment == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                $paymentinfo = Payment::get(['out_trade_no'=>$out_trade_no]);
                //你可以在此编写订单逻辑
                if($platform == 'shop'){
                    $order = ShopOrder::where('order_sn', $out_trade_no)->find();
                    if (!$order || $order->status != 0) {
                        // 订单不存在，或者订单已支付
                        return $pay->success()->send();
                    }
                    //订单支付完成时同步支付流水状态
                    $this->syncPaymentInfo($out_trade_no, $data, $paymentinfo);
                    //更新订单状态
                    $arr = [
                        'status'=>1,
                        'transaction_id'=>$payment == 'alipay' ? $data['trade_no'] : $data['transaction_id'],
                        'pay_type'=>$payment,
                        'paytime'=>time(),
                        'pay_fee'=>$pay_fee,
                    ];
                    ShopOrder::where(['id'=>$order['id']])->update($arr);

                    //判断是否存在上级 且上级身份
                    $user = User::where(['id'=>$order['user_id']])->find();
                    if(!empty($user['invite_user_id'])){
                        $invite_user = User::where(['id'=>$user['invite_user_id']])->find();
                        //计算分佣金额
                        $price = bcdiv($pay_fee, 20, 2);//分佣百分之五
                        if($invite_user['is_agent'] == 2){ //是苏拉代理商
                            $arr = [
                                'giveaway_price'=>bcadd($invite_user['giveaway_price'],$price,2),
                                'shop_price'=>bcadd($invite_user['shop_price'],$price,2),
                            ];
                            User::where(['id'=>$invite_user['id']])->update($arr);
                        }else{
                            //不是代理商查询是否是第一次充值
                            $info = ShopPriceLog::where(['user_id'=>$order['user_id'],'type'=>2])->find();
                            if(!$info){
                                $arr = [
                                    'giveaway_price'=>bcadd($invite_user['giveaway_price'],$price,2),
                                    'shop_price'=>bcadd($invite_user['shop_price'],$price,2),
                                ];
                                User::where(['id'=>$invite_user['id']])->update($arr);
                            }
                        }
                    }

                    $shop = Shop::where(['id'=>$order['shop_id']])->find();
                    if($order['is_ai']){ //ai套餐充值
                        //增加商户AI使用次数
                        Shop::where(['id'=>$order['shop_id']])->update(['ai_num'=>$shop['ai_num']+$order['ai_num']]);
                    }else{
                        //增加商户账号余额
                        $shop = Shop::where(['id'=>$order['shop_id']])->find();
                        $ai_num =  intdiv($pay_fee, 5);;
                        $data = ['ai_num'=>$shop['ai_num']+$ai_num];

                        if($order['type'] == 1){
                            $data['balance'] = $shop['balance']+$pay_fee;
                        }elseif($order['type'] == 2){
                            $data['enemy_num'] = $shop['enemy_num']+$order['num'];
                        }elseif($order['type'] == 3){
                            $data['thirdpartnar_num'] = $shop['thirdpartnar_num']+$order['num'];
                        }elseif($order['type'] == 4){
                            $data['monthly_num'] = $shop['monthly_num']+$order['num'];
                        }
                        Shop::where(['id'=>$order['shop_id']])->update($data);
                        //记录日志数据
                        $arr = [
                            'user_id'=>$order['user_id'],
                            'shop_id'=>$order['shop_id'],
                            'price'=>$pay_fee,
                            'type'=>2,
                            'add_time'=>time(),
                            'shop_order_id'=>$order['id'],
                            'consumption_type'=>$order['type']
                        ];
                        ShopPriceLog::insert($arr);
                    }
                }else{
                    $order = UserOrder::where('order_id', $out_trade_no)->find();
                    if (!$order || $order->status != 1) {
                        // 订单不存在，或者订单已支付
                        return $pay->success()->send();
                    }
                    //订单支付完成时同步支付流水状态
                    $this->syncPaymentInfo($out_trade_no, $data, $paymentinfo);
                
                    $notify = [
                        'order_sn' => $data['out_trade_no'],
                        'transaction_id' => $payment == 'alipay' ? $data['trade_no'] : $data['transaction_id'],
                        'notify_time' => date('Y-m-d H:i:s', strtotime($data['time_end'])),
                        'buyer_email' => $order->user_id,
                        'payment_json' => json_encode($data),
                        'pay_fee' => $pay_fee,
                        'pay_type' => $payment// 支付方式
                    ];
                    $this->paymentProcess($order, $notify);

                    //  下单后标为售出
                    $product = Product::where(['id'=>$order['product_id']])->find();
                    $this->sendOrderSuccess($order,$product);
                    //发送成功给卖家发送消息
                    $geTui = new GeTui();
                    //添加成功执行推送逻辑
                    $cid = User::where(['id'=>['in',$data['shop_id']]])->value('cid');
                    if($cid){
                        $geTui->pushToSingleByCid($cid,'订单提醒','您的商品已被兑换,请前往发货','/pages/user/sellOrder');
                    }
                }
                return $pay->success()->send();
           } catch (\Exception $e) {
            }
       });

        return $result;
    }
    //更新订单状态
    private function paymentProcess($order, $notify) {

        $order->status = 2;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = $notify['payment_json'];
        $order->pay_type = $notify['pay_type'];
        $order->pay_fee = $notify['pay_fee'];
        $order->save();

        

        /* //记录订单操作日志
        $oper_id = empty($oper) ? 0 : (is_array($oper) ? $oper['id'] : $oper->id);
        $self = new OrderAction();
        $self->order_id = $order['id'];
        $self->order_item_id = is_null($order) ? 0 : $order['id'];
        $self->oper_type = 'user';
        $self->oper_id = $oper_id;
        $self->order_status = is_null($order) ? 0 : $order['status'];
        $self->dispatch_status = is_null($order) ? 0 : $order['dispatch_status'];
        $self->comment_status = is_null($order) ? 0 : $order['comment_status'];
        $self->aftersale_status = is_null($order) ? 0 : $order['aftersale_status'];
        $self->refund_status = is_null($order) ? 0 : $order['refund_status'];
        $self->remark = '用户支付成功';
        $self->save(); */
    }

    
	//下单成功后操作
	private function sendOrderSuccess($data,$product){
		//  下单后标为售出
		Product::where(array('id'=>$data['product_id']))->update(array('is_sale'=>1));
		roseandlog($data['user_id'],0-$data['total_money'],5,'兑换商品扣除');
		ProductMessage::insert(array('product_id'=>$data['product_id'],'message_id'=>0,'title'=>'买家'.User::where('id',$data['user_id'])->value('nickname').'下单了，请尽快发货:【'.$product['title'].'】','user_id'=>$data['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
		$configuration=Configuration::where(array('id'=>1))->find();
		// 注意使用GMT时间  
		date_default_timezone_set("GMT");  
		$target = "https://dysmsapi.aliyuncs.com/?";  
		$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范  
		$accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
		$accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
		$ParamString="{}";
		$mobile=$product['phone'];
		$data = array(  
			'AccessKeyId' => $accessKeyId,
			'Action' => 'SendSms',
			'Format' => 'XML', 
			'OutId' => '123',
			'PhoneNumbers' => $mobile,
			'RegionId' => 'cn-hangzhou',
			'SignName'=>$configuration['sign_name'],
			'SignatureMethod' => 'HMAC-SHA1',
			'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			'SignatureVersion' => '1.0',
			'TemplateCode' => 'SMS_274540075', 
			'TemplateParam' => $ParamString,
			'Timestamp' => date("Y-m-d H:i:s"), 
			'Version' => '2017-05-25'
		);  
		$data['Signature'] = computeSignature($data, $accessKeySecret);  
		// 发送请求  
		$result = xml_to_array(https_request($target.http_build_query($data)));
		//print_r($result);
		if(!empty($result['Error']['Message'])){
			$this->error($result['Error']['Message']);
		}

        if($product['notice'] == 0){
			return true;
		}
        //发送订阅消息
		$data = [
			"thing8"=>["value"=>$product['title']],
            "thing3"=>[ "value"=> '待发货'], 
            "thing4"=>["value"=>'你的闲置已赠出，请去订单页进行预约取件！' ]
		];
		send_subscription($product['user_id'],'UJnRdmFH3FHRqisFtbKCuYJRxHEK1J8sJydn0DToLFg','/pages/user/sellOrder',$data);
	}
    
    /**
     * 同步支付流水的结果
     * @param $out_trade_no
     * @param $data
     * @param $payment
     * @return void
     * @throws \think\exception\DbException
     */
    private function syncPaymentInfo($out_trade_no, $data, $payment) {
        $paymentinfo = Payment::get(['out_trade_no'=>$out_trade_no]);

        $pay_fee = $payment == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;

        $paymentinfo['updatetime'] = time();
        $paymentinfo['pay_amount'] = $pay_fee;
        $paymentinfo['status'] = 'success';
        $paymentinfo['pay_json'] = json_encode($data, JSON_UNESCAPED_UNICODE);
        $paymentinfo['transaction_id'] = $payment == 'alipay' ? $data['trade_no'] : $data['transaction_id'];
        $paymentinfo['pay_time'] = time();
        $paymentinfo->save();
    }

  
    /**
     * 获取用户openid
     * @param $code
     * @return mixed|void
     */
    public function LightOpenID($code) {

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->appid.'&secret='.$this->secret.'&js_code='.$code.'&grant_type=authorization_code';

        $result = file_get_contents($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取openid时异常，微信内部错误');
        } else {
            if (array_key_exists('errcode', $wxResult)) {
                $this->error($result);
            } else {
                return $openid = $wxResult['openid'];
            }
        }
    }



    /**
     * 订单执行退款
     * @param $order  订单数据
     * @param $refund_money  退款金额
     * @return void
     * @throws \think\exception\DbException
     */
    public static function doOrderRefund($order, $refund_money, $nickname,$arr) {
       
        $paymentinfo = Payment::get(['out_trade_no'=>$order['order_id']]);
        if(!$paymentinfo){
            //未查询到退款订单数据
            $arr['text'] = '未查询到退款订单数据';
            db('order_log')->insert($arr);
            return true;
        }
        $out_refund_no = date("YmdHis".$order['id']);
        switch ($order['pay_type']) {
            case 'wechat':
                $refund_data = [
                    'out_trade_no'=>$order['order_id'],
                    'out_refund_no'=>$out_refund_no,
                    'total_fee'=>$order['pay_fee']*100,
                    'refund_fee'=>$refund_money*100,
                ];
                break;
            case 'alipay':
                $refund_data = [
                    'out_trade_no'=>$order->order_sn,
                    'refund_amount'=>$order->pay_fee,
                ];
                break;
            default:
                $arr['text'] = '错误的支付方式';
                db('order_log')->insert($arr);
                throw new \Exception('错误的支付方式');
                break;
        }

        $pay = new PayService($order['pay_type'], $paymentinfo['platform']);
        $result = $pay->refund($refund_data);


        if((isset($result['return_code'])&&$result['return_code']=='SUCCESS')||(isset($result['trans_state'])&&$result['trans_state']=='S')){
            //添加退款记录
            $row = [
                'type'=>'refund',
                'pay_type'=>$order->pay_type,
                'order_id'=>$order->id,
                'out_trade_no'=>$paymentinfo['out_trade_no'],
                'createtime'=>time(),
                'updatetime'=>time(),
                'pay_time'=>time(),
                'amount'=>$refund_money,
                'pay_amount'=>$refund_money,
                'status'=>'success',
                'pay_json'=>json_encode($result, JSON_UNESCAPED_UNICODE),
                'payment_id'=>$out_refund_no,
                'transaction_id'=>$result['transaction_id']??$result['payment_id'],
                'refund_id'=>$result['refund_id']??$result['id'],
                'user_id'=>$order->user_id,
                'platform'=>$paymentinfo->platform,
                'use_type'=>'order',
            ];
            Payment::insert($row);

            //退款成功后操作逻辑
            
            //退回积分
            roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
            $product=Product::where(array('id'=>$order['product_id']))->find();
            ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$nickname.'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
            Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));

            $arr['text'] = '退款成功';
            db('order_log')->insert($arr);
        }else{
            $arr['text'] = '退款失败';
            db('order_log')->insert($arr);
            throw new \Exception('退款失败');
        }
    }

    

}